import random
import math
import matplotlib.pyplot as plt
# 设置随机种子以确保生成的点相同
import matplotlib.patches as patches

# 生成随机点
# step 1
def generate_random_points(n, min_radius=1.0, max_radius=1.5):
    points = []
    for _ in range(n):
        # 随机生成角度
        angle = random.uniform(0, 2 * math.pi)
        # 随机生成半径
        radius = random.uniform(min_radius, max_radius)
        # 计算 x 和 y 坐标
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        # y = 1.0
        points.append((x, y))
    return points


# 将直角坐标转换为像素坐标
# step2  
def convert_to_pixel_coordinates(points, origin=(300, 300), scale=100):
    pixel_points = []
    for x, y in points:
        # 转换为像素坐标，注意 Y 轴翻转
        px = origin[0] + scale * x
        py = origin[1] - scale * y
        # xy  origin
        # px py 像素点
        pixel_points.append((px, py, x, y))
    return pixel_points

# 极坐标转换函数
def xy2rtheat(points, origin=(300, 300)):
    points_pole = []
    for px, py, x, y in points:
        # 将像素坐标平移到原点
        # cx = px
        # cy = py
        # px = px - origin[0]
        # py = origin[1] - py  # 注意 Y 轴翻转
        # 计算极坐标
        r = math.sqrt(x**2 + y**2)
        theta = math.atan2(y, x)  # atan2 返回 [-π, π]
        if theta < 0:
            theta += 2 * math.pi  # 将角度调整到 [0, 2π)
        # points_pole.append((cx, cy, px, py, x, y, r, theta))
        points_pole.append((px, py, x, y, r, theta))
    # 按照 theta 排序
    points_pole_sorted = sorted(points_pole, key=lambda point: point[5])
    return points_pole_sorted

def filter_points_by_theta(data, angle=10, dis=0.2):
    # 初始化 need 和 unneed 列表
    need = []
    unneed = []
    
    # 角度差的阈值（角度转换为弧度）
    angle_threshold = angle * math.pi / 180  # 5度 = 5/180 * π
    
    # 如果数据为空，直接返回
    if not data:
        return need, unneed
    
    # 第一个点直接加入 need
    need.append(data[0])
    
    # 遍历从第二个点开始的数据
    for i in range(1, len(data)):
        # 当前点和前一个点
        current = data[i]
        previous = need[-1]  # 取 need 中最后一个点作为前一个点
        
        # 提取当前点和前一个点的 (x, y, r, theta)
        # px, py, cx ,cy, x, y, r, theta
        px_current, py_current,x_current, y_current, r_current, theta_current = current
        px_previous, py_previous, x_previous, y_previous, r_previous, theta_previous = previous
        
        # 计算两点之间的欧几里得距离
        distance = math.sqrt((x_current - x_previous)**2 + (y_current - y_previous)**2)
        theta_gap = abs(theta_current - theta_previous) 
        # print(theta_current * 57, theta_previous * 57, theta_gap * 57)

        if theta_gap >= angle_threshold :
            need.append(current)
        elif theta_gap < angle_threshold:
            if r_current >= r_previous:
                unneed.append(current)
            # 在前面
            elif r_current < r_previous:
                if distance > dis:
                    # if need is not None:
                    unneed.append(need.pop())
                    need.append(current)
                
                else:
                    unneed.append(current)
                    


    
    return need, unneed


# random.seed(42)  # 你可以选择任何整数作为种子值
n = 50  # 你可以改变这个值

random_points = generate_random_points(n)
# print(random_points[:1])
# 转换随机点为像素坐标
pixel_points = convert_to_pixel_coordinates(random_points)
# print(pixel_points[:1])
# 转换为极坐标
pixel_pole = xy2rtheat(pixel_points)
# print(pixel_pole[:1])
print("转换为极坐标并排序：")
for px, py, x, y, r, theta in pixel_pole:
    theta_deg = theta * 57.2958  # 弧度转为度
    print(f"像素坐标: ({px:.2f}, {py:.2f}), ({x:.2f}, {y:.2f}), r: {r:.2f}, θ: {theta_deg:.2f}°")



need, unneed = filter_points_by_theta(pixel_pole, 5, 0.2)
print("need")
for px, py, x, y, r, theta in need:
    theta_deg = theta * 57.2958  # 弧度转为度
    print(f"像素坐标: ({px:.2f}, {py:.2f}), ({x:.2f}, {y:.2f}), r: {r:.2f}, θ: {theta_deg:.2f}°")

print("unneed")
for px, py, x, y, r, theta in unneed:
    theta_deg = theta * 57.2958  # 弧度转为度
    print(f"像素坐标: ({px:.2f}, {py:.2f}),  ({x:.2f}, {y:.2f}), r: {r:.2f}, θ: {theta_deg:.2f}°")


print(f'need {need.__len__()}')
print(f'need {unneed.__len__()}')

# 绘制图像
plt.figure(figsize=(6, 6))

# 将左上角设为 (0, 0)，右下角为 (600, 600)
plt.xlim(0, 600)
plt.ylim(600, 0)  # 注意 Y 轴翻转

# 绘制辅助线
plt.axhline(y=300, color='gray', linestyle='--', linewidth=0.5)
plt.axvline(x=300, color='gray', linestyle='--', linewidth=0.5)

# 绘制原点和随机点
plt.scatter(300, 300, color='yellow', label='Origin (0, 0)', s=100)
# plt.scatter([p[0] for p in pixel_points], [p[1] for p in pixel_points], color='blue', label='Random Points', s=50)
plt.scatter([p[0] for p in need], [p[1] for p in need], color='blue', label='Random Points', s=10)
# plt.scatter([p[0] for p in unneed], [p[1] for p in unneed], color='red', label='Random Points', s=10)
rect = patches.Rectangle(
    (276, 248),  # 左上角坐标
    324 - 276,   # 矩形的宽度
    316 - 248,   # 矩形的高度
    linewidth=1, edgecolor='gray', facecolor='none'
)
plt.gca().add_patch(rect)

rect1 = patches.Rectangle(
    (150, 150),  # 左上角坐标
    450 - 150,   # 矩形的宽度
    450 - 150,   # 矩形的高度
    linewidth=1, edgecolor='black', facecolor='none'
)
plt.gca().add_patch(rect1)
# 设置标题和标签
plt.title('Random Points Around Origin within Radius 1.0 to 1.5m')
plt.xlabel('X-axis (pixels)')
plt.ylabel('Y-axis (pixels)')
plt.legend()
plt.grid()
plt.gca().set_aspect('equal', adjustable='box')
# plt.savefig('index1.png', dpi=300, bbox_inches='tight')  # 保存为 PNG 格式，分辨率为 300 DPI
plt.savefig('index0.png', dpi=300, bbox_inches='tight')  # 保存为 PNG 格式，分辨率为 300 DPI
plt.scatter([p[0] for p in unneed], [p[1] for p in unneed], color='red', label='Random Points', s=10)

plt.savefig('index1.png', dpi=300, bbox_inches='tight')  # 保存为 PNG 格式，分辨率为 300 DPI

# 显示图像
# plt.show()
